package com.eiisan.weixin.mp.handler;

import com.eiisan.base.constant.GlobalConstant;
import com.eiisan.core.util.api.Result;
import com.eiisan.user.feign.UserClientApi;
import com.eiisan.util.RegexUtil;
import com.eiisan.weixin.mp.builder.TextBuilder;
import com.eiisan.weixin.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author Binary Wang(https://github.com/binarywang)
 */
@Slf4j
@Component
public class MsgHandler extends AbstractHandler {

    // 用户发送手机验证码提示
    @Value("${eiisan.weixin.registration.code.message}")
    private String registrationCodeMessage;
    // 默认用户发送验证码提示
    @Value("${eiisan.weixin.default.registration.code.message}")
    private String defaultRegistrationCodeMessage;

    @Autowired
    UserClientApi UserClientApi;

    @Autowired
    private RedisService redisService;


    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService weixinService,
                                    WxSessionManager sessionManager) {

        if (!wxMessage.getMsgType().equals(WxConsts.XmlMsgType.EVENT)) {
            // TODO 可以选择将消息保存到本地
        }

        // 当用户输入关键词如“你好”，“客服”等，并且有客服在线时，把消息转发给在线客服
        try {
            if (StringUtils.startsWithAny(wxMessage.getContent(), "你好", "客服")
                    && weixinService.getKefuService().kfOnlineList().getKfOnlineList().size() > 0) {
                return WxMpXmlOutMessage.TRANSFER_CUSTOMER_SERVICE().fromUser(wxMessage.getToUser())
                        .toUser(wxMessage.getFromUser()).build();
            }
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        // 1. 获取微信客户端发送的消息
        String fromContent = wxMessage.getContent();
        // 2.使用正则表达式验证消息是否为手机号码格式
        if (RegexUtil.checkMobile(fromContent)) {
            String content = "";
            //3.查询手机号是否已存在
            Result<Boolean> result = null;
            try {
                result = UserClientApi.checkMobile(fromContent);
            } catch (Exception e) {
                //e.printStackTrace();
                log.error(e.getMessage());
                content = "服务异常";
                return new TextBuilder().build(content, wxMessage, weixinService);
            }
            //3.1调用出错 或返回错误result
            if(result == null){
                content = "服务异常";
                return new TextBuilder().build(content, wxMessage, weixinService);
            }
            if(Result.isNotSuccess(result)){
                content = result.getMessage();
                return new TextBuilder().build(content, wxMessage, weixinService);
            }
            //3.2正常返回，判断是否存在手机号
            if(result.getData()) {
                content = "该手机号已注册";
                return new TextBuilder().build(content, wxMessage, weixinService);
            }
            
            // 4.如果是手机号码格式的话,随机生产4位数字注册码
            int registCode = registCode();
            content = String.format(registrationCodeMessage, registCode);
            // 5.将验证码存放在Redis中
            redisService.setKey(GlobalConstant.WeiXin.REGISTER_CODE_KEY + fromContent,
                    String.valueOf(registCode), GlobalConstant.WeiXin.REGISTER_CODE_EXPIRE, TimeUnit.MINUTES);

            return new TextBuilder().build(content, wxMessage, weixinService);
        }
        // 否则情况下返回默认消息（或者调用第三方机器人智能回答）
        return new TextBuilder().build(defaultRegistrationCodeMessage, wxMessage, weixinService);
    }

    // 获取注册码
    private int registCode() {
        int registCode = (int) (Math.random() * 9000 + 1000);
        return registCode;
    }
}
